//app.js
App({
  onLaunch: function () {
    let that = this;
    // 全局里有没有openID
    if (!that.globalData.opid) {
      // 获取code
      wx.login({
        success: function (login) {
          that.globalData.code = login.code;
          console.log(login.code)
        }
      })
      that.globalData.loginState = true
    }
    // console.log(wx.getStorageSync('opid'))
    // 本地存储有没有openID
    if (!wx.getStorageSync('opid')) {
      wx.getSetting({
        success(res) {
          console.log(res)
          if (res.authSetting['scope.userInfo']) {
            that.globalData.loginState = false
            wx.getUserInfo({
              success: function (res) {
                console.log(res);
                that.globalData.loginFn(res.userInfo)
              }
            })
          } else {
            that.globalData.loginState = true
          }
        }
      })
    }
    that.globalData.loginFn = function (userInfo) {
      console.log(userInfo)
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      wx.request({
        url: that.globalData.url + 'wxlogin.php',
        data: {
          name:
            JSON.stringify({
              code: that.globalData.code,
              user: that.globalData.userInfo
            })
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (loginOk) {
          console.log(loginOk)
          wx.setStorageSync('opid', loginOk.data.openid)
          wx.setStorageSync('userStatus', loginOk.data.user_rank)
          that.globalData.opid = loginOk.data.openid
          that.globalData.userStatus = loginOk.data.user_rank
          that.globalData.userInfo = userInfo
          wx.hideLoading()
        }
      })
    }
    that.globalData.loginFn
  },
  globalData: {
    url: 'https://rt.gzziyu.com/mobile/',
    opid: wx.getStorageSync('opid'),
    userInfo: wx.getStorageSync('userInfo'),
    loginState: ''
  }
})